<template>
    <div>
        <table border style="width: 800px">
            <thead>
                <tr>
                    <th>名称</th>
                    <th>数量</th>
                    <th>单价</th>
                    <th>操作</th>
                </tr>
            </thead>   
            <tbody>
                <tr v-for="(item, index) in tableData" :key="index">
                    <td>{{item.name}}</td>
                    <td><button @click="addAndSub(item, false)">-</button>{{item.num}}<button @click="addAndSub(item, true)">+</button></td>
                    <td>{{item.price * item.num}}</td>
                    <td><button @click="del(index)">删除</button></td>
                </tr>
            </tbody> 
            <tfoot>
                <td colspan="4">总价：{{$total}}</td>
            </tfoot>
        </table>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, computed } from 'vue'

type Shop = {
    name: string,
    num: number,
    price: number
}

const tableData = reactive<Shop[]>([
    {
        name: '上衣',
        num: 1,
        price: 200
    },
    {
        name: '裤子',
        num: 1,
        price: 100,
    },
    {
        name: '鞋子',
        num: 1,
        price: 300,
    }
])

let $total = ref(0)

const addAndSub = (item: Shop, type: boolean): void => {
    if(item.num > 1 && !type) {
        item.num--;
    }
    if(item.num < 99 && type) {
        item.num++;
    }
    // total()
}

const del = (i: number):void => {
    tableData.splice(i, 1)
    // total()
}

// const total = () => {
//     $total.value = tableData.reduce((prev, next) => {
//         return prev + (next.num * next.price)
//     }, 0)
// }
// total()

// 使用computed
$total = computed<number>(() => {
    return tableData.reduce((prev, next) => {
        return prev + (next.num * next.price)
    }, 0)
})
</script>

<style scoped>

</style>